/**
 * add an new query parameters to url
 *
 * @param {string} url - url, maybe with ?, # or not
 * @param {string} query - such as 'foo=bar&hello=world'
 * @param {Array} excluded - The excluded key in query
 * @return {string} - the merged url
 */
export default function mergeUrl(url, query, excluded) {
    if (!url) return '';
    if (!query) return url;

    query = query.replace(/^\?/, '');
    query = excludeFieldBy(query, excluded);
    query = query.replace(/\&$/, '');

    if (!query) return url;

    if (url.indexOf('#') !== -1) {
        var parts = url.split('#');
        return mergeUrl(parts[0], query) + '#' + parts[1];
    }

    if (url.indexOf('?') !== -1) {
        return url + '&' + query;
    }

    return url + '?' + query;
}

function excludeFieldBy(query, arr) {
    if (!query) return '';
    if (!arr || arr.length <= 0) return query;

    var result = query;

    arr.forEach(function (key) {
        var reg = new RegExp('\\b' + key + '=[^=&]+&?', 'g');
        result = result.replace(reg, '');
    });

    return result;
}
